import React, { useState } from "react";
import Taro from "@tarojs/taro";
import { View, Image, Button, Radio, Text } from "@tarojs/components";
import { AtToast } from "taro-ui";

import api from "@api/api.js";
import { AES } from "@util/util";
import "./index.less";

export default (props) => {
  const [toast, setToast] = useState({ text: "", isOpened: false });
  const getUserInfo = () => {
    Taro.getUserInfo({
      success(res) {
        const { iv, encryptedData, signature } = res;
        Taro.login({
          async success(res) {
            const { code } = res;
            const { data } = await api.login({
              code,
              iv,
              encryptedData,
              signature,
            });
            Taro.setStorageSync("token", AES(data.accessToken));
            Taro.setStorageSync("refreshToken", AES(data.refreshToken));
            setToast({
              text: "登录成功",
              isOpened: true,
              onClose: () => {
                Taro.navigateBack({
                  delta: 1,
                });
              },
            });
          },
        });
      },
    });
  };
  return (
    <View className="login">
      <AtToast {...toast}></AtToast>
      <View className="logo">
        <Image />
      </View>
      <View className="myRadio">
        <Radio>
          我已阅读并同意<Text>【用户协议】</Text>
        </Radio>
        <Button openType="getUserInfo" onGetUserInfo={getUserInfo}>
          登录
        </Button>
      </View>
    </View>
  );
};
